package controller;


import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.Model;
import model.UserDAO;

import org.mybeans.form.FormBeanException;
import org.mybeans.form.FormBeanFactory;

import databean.User;
import formbean.UserLoginForm;


public class UserLoginAction extends Action {
	private FormBeanFactory<UserLoginForm> formBeanFactory = FormBeanFactory.getInstance(UserLoginForm.class);
	
	private UserDAO userDAO;

	public UserLoginAction(Model model) {
		userDAO = model.getUserDAO();
	}

	public String getName() { return "user-login.do"; }
    
    public String perform(HttpServletRequest request,HttpServletResponse response) {
        List<String> errors = new ArrayList<String>();
        request.setAttribute("errors",errors);
        HttpSession session = request.getSession();
        
        try {
	        
	        UserLoginForm form;
			
		    form = formBeanFactory.create(request);
			 
	        request.setAttribute("form",form);
	        	        

	        // If no params were passed, return with no errors so that the form will be
	        // presented (we assume for the first time).
	        if (!form.isPresent()) {
	            return "user-login.jsp";
	        }

	        // Any validation errors?
	        errors.addAll(form.getValidationErrors());
	        if (errors.size() != 0) {
	            return "user-login.jsp";
	        }


	        
	        
	        // Look up the user	        
	        if (!userDAO.checkValidUserName(form.getUserName())) {
	        	//User Name not found
	        	errors.add("Incorrect Username or Password");
	            return "user-login.jsp";
	        }

	        User user = new User();
	        user = userDAO.getUserByUsername(form.getUserName());
	        
	        // Check the password
	        if (!user.checkPassword(form.getPassword())) {
	        	//Incorrect password
	        	errors.add("Incorrect Username or Password");
	            return "user-login.jsp";
	        }
	
	        // Attach (this copy of) the customer bean to the session	        
	        session.setAttribute("user",user);
		    
			String webapp = request.getContextPath();
			return webapp + "/conversation-feed.do";
			
        } catch (SQLException e) {
			e.printStackTrace();
        	errors.add(e.getMessage());
        	return "user-login.jsp";
        } catch (FormBeanException e) {
			e.printStackTrace();
        	errors.add(e.getMessage());
			return "user-login.jsp";
		}
    }
}
